import { createOrder, prePay } from "@/api/order";
import Cookies from "@/utils/cookies";

export default {
  namespaced: true,
  state: {
    infoForm: {},
    orderId: null,
  },
  mutations: {
    setInfoForm(state, form) {
      state.infoForm = form;
    },
    setOrderId(state, id) {
      state.orderId = id;
    },
  },
  actions: {
    async cerateOrder({ rootGetters, rootState, commit, state }) {
      let createOrderQuery = {
        platformType: rootGetters["Public/getPlatformType"],
        appId: rootState.Public.appId,
        userId: rootState.user.user.id,
        token: rootState.user.user.token,
        contract: ["privacy_agreement"],
        ...state.infoForm,
      };
      try {
        const order_auth_code = await my.getAuthCode({ scopes: "order_service" });
        console.log(order_auth_code.authCode);
        // 生成订单时,需要从其他地方哪取关联数据
        createOrderQuery.authCode=order_auth_code.authCode
      } catch (error) {
        console.log(error);
      }
      const res = await createOrder(createOrderQuery);
        if (res.code === 200) {
          uni.navigateTo({
            url: `/pages/checkCredit/payment?orderId=${res.data.id}`,
          });
        }
      // commit("setOrderId", order.data.id);
    },

    async goPrePay({ state,commit }, id) {
      commit("setInfoForm", {});
      let timeoutId;
      id = typeof id !== "undefined" ? id : state.orderId;
      const res = await prePay(id);
      my.tradePay({
        tradeNO: res.data.tradeNo,
        success: function(res) {
          // 跳转订单用
          // 支付成功跳转订单-查询报告列表页面
          if (res.resultCode === "9000") {
            uni.showLoading({
              title: "正在生成报告请稍等",
            });
            timeoutId = setTimeout(function() {
              clearTimeout(timeoutId);
              uni.hideLoading();
              uni.reLaunch({ url: `/pages/index/report?orderId=${id}` });
            }, 2500);
          } else if (res.resultCode === "6001") {
            // 取消支付跳转订单-预支付页面
            uni.reLaunch({ url: "/pages/order/index?currentTab=1" });
          }
        },
        fail: function(res) {
          console.log("fail", res);
          // 支付失败跳转订单-预支付页面
          uni.reLaunch({ url: "/pages/order/index?currentTab=1" });
        },
      });
    },
  },
};
